package com.lagou.rpc.consumer.configuration;

import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.lang.Nullable;

public class RpcFactoryBean<T> implements FactoryBean<T>,InitializingBean {
    private String interfaceName;
    private Class<T> rpcInterface;

    @Nullable
    @Override
    public T getObject() throws Exception {
        if (this.rpcInterface == null){
            this.rpcInterface = (Class<T>) Class.forName(interfaceName);
        }
        return (T) RpcClientProxy.createProxy(this.rpcInterface);
    }

    @Nullable
    @Override
    public Class<?> getObjectType() {
        return this.rpcInterface;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (this.rpcInterface == null){
            this.rpcInterface = (Class<T>) Class.forName(interfaceName);
        }
    }

    public Class<T> getRpcInterface() {
        return rpcInterface;
    }

    public void setRpcInterface(Class<T> rpcInterface) {
        this.rpcInterface = rpcInterface;
    }

    public String getInterfaceName() {
        return interfaceName;
    }

    public void setInterfaceName(String interfaceName) {
        this.interfaceName = interfaceName;
    }
}
